package com.github.lh.controller;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author <a href="mailto: 393803588@qq.com">刘涵(Hanl)</a>
 * By 2018/1/12
 */
@RestController
public class DefaultController {

    final WebDriver driver;

    {
        System.setProperty("phantomjs.binary.path", "/home/hanl/phantomjs-2.1.1-macosx/bin/phantomjs");

        DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs();
        desiredCapabilities.setCapability("phantomjs.page.settings.userAgent",
                "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36");

        this.driver = new PhantomJSDriver(desiredCapabilities);
    }

    @GetMapping("/render")
    public ResponseEntity<?> agent(String url) {
        driver.get(url);
        String html = this.driver.getPageSource();

        Document doc = Jsoup.parse(html);
        return ResponseEntity.ok(doc.toString());
    }
}
